import { message } from "ant-design-vue";
import { ref } from "vue";
export function useFetch<T = any>(
  a: Function = (c: T) => c,
  {
    successMsg = "",
    showSuccess = false,
    errorMsg = "",
    showError = true,
    status = 200,
    params = null,
    afterFetch = (c: T) => c,
  } = {},
  c: Function = (c: T) => c,
) {
  const loading = ref(false);
  const data = ref();
  function reload() {
      loading.value = true;
      a(params)
        .then((res: any) => {
          if (res.status == status) {
            loading.value = false;
            afterFetch(res.data);
            c(res.data)
            data.value = res.data;
            if (showSuccess || !!successMsg) {
              if (!!successMsg) {
                message.success(successMsg);
              } else {
                message.success(res.message);
              }
            }
          } else {
            if (showError || !!errorMsg) {
              if (!!errorMsg) {
                message.error(errorMsg);
              } else {
                message.error(res.message);
              }
            }
          }
        })
        .catch(() => {
          loading.value = false;
        });
  }

  function init() {
    reload();
  }
  init();
  return { loading, data, reload };
}
